<?php

namespace Xcx\Controller;

use Think\Controller;
use Think\Log;
use Xcx\Common\ErrorCode;
use Xcx\Model\LoginModel;

header('Content-type:text/html;chatset=utf-8');
class LoginController extends Controller
{

    protected $errMsg = '';

    public function __construct(){
        parent::__construct();
    }

    /**
     * 获取小程序与后端通信的session_id
     */
    public function getSessionId()
    {
        $sessionId = session_id();
        if ($sessionId) {
            $arr['code'] = '0';
            $arr['errMsg'] = 'sessionId获取成功';
            $arr['session_id'] = $sessionId;
        }
        $this->ajaxReturn($arr);
    }

    /**
     * 检查用户是否关注过公众号
     */
    public function checkIsFollowed()
    {
        $code = I("code");
        $WXLogin = new WXLoginHelperController();
        $userData = $WXLogin->checkIsFollow($code);

        if ($userData['code'] != 0) {
            $arr = array('code'=>$userData['code'],'msg'=>$userData['message']);
            $this->ajaxReturn($arr);
        }
//        $unionid = $userData['unionid'];
        $openid = $userData['openid'];
        $m = new LoginModel();
        //通过unionid检查用户是否存在
        //用户不存在则新增用户
        if ($m->checkUserIsExist($openid)) {
            //设置用户后端登录
            $userinfo = $this->setActiveUser($openid, $userData['session3rd'], $userData['session_key']);
            if ($userinfo) {
                //将用户数据返回到小程序
                $arr = array('code'=>0,'userInfo'=>$userinfo ,'session3rd'=>$userData['session3rd']);
            } else {
                $arr = array('code'=>ErrorCode::$Fail,'msg'=>'用户登录失败1');
            }
        } else {
            //该用户不存在于后台数据库，则返回0，前端继续调用用户授权获取信息，存入后端数据库
            $arr = array('code'=>ErrorCode::$NoFollow,'userInfo'=>$userData ,'session3rd'=>$userData['session3rd']);
        }
        $this->ajaxReturn($arr);
    }

    /**
     * 小程序用户登录
     * 如果数据库不存在该用户则新增该用户数据后再登录
     * 如果数据库存在该用户则直接登录
     */
    public function doLogin()
    {
        $sessionKey = I("session_key");
        $rawData = I("rawData");
        $signature = I("signature");
        $encryptedData = I("encryptedData");
        $iv = I("iv");
        //获取unionid
        $WXLogin = new WXLoginHelperController();
        $userData = $WXLogin->checkLogin($sessionKey, $rawData, $signature, $encryptedData, $iv);

//        if (!isset($userData['unionId'])) {
//            $arr = array('code'=>$userData['code'],'msg'=>$userData['message']);
//            $this->ajaxReturn($arr);
//        }
//        $unionid = $userData['unionId'];
        if (!isset($userData['openId'])) {
            $arr = array('code'=>$userData['code'],'msg'=>$userData['message']);
            $this->ajaxReturn($arr);
        }

        $openId = $userData['openId'];
        $m = new LoginModel();
        //通过unionid检查用户是否存在
        //用户不存在则新增用户
        if (!$m->checkUserIsExist($openId)) {
            $headerImage = saveUserHeadImg($userData['avatarUrl']);
            $dataArr['nickname'] = $userData['nickName'];
            $dataArr['header'] = $headerImage;
//            $dataArr['unionid'] = $unionid;
            $dataArr['openid'] = $userData['openId'];
            $dataArr['since_from'] = 1;
            $dataArr['add_time'] = time();
            if(!$m->addUserInfo($dataArr)) {
                $this->ajaxReturn(array('code'=>ErrorCode::$Fail,'msg'=>'信息存入失败'));
            }
        }
        //设置用户后端登录
        $userinfo = $this->setActiveUser($openId, $userData['session3rd'], $sessionKey);
        if ($userinfo) {
            //将用户数据返回到小程序
            $arr = array('code'=>'0','userInfo'=>$userinfo ,'session3rd'=>$userData['session3rd']);
        } else {
            $arr = array('code'=>ErrorCode::$Fail,'msg'=>'用户登录失败');
        }
        $this->ajaxReturn($arr);

    }

    /**
     * @param $openId
     * @param $session3rd
     * @param $sessionKey
     * @return array|bool|false|mixed|\PDOStatement|string|\Think\Model
     */
    private function setActiveUser($openId, $session3rd, $sessionKey) {
        $LoginModel = new LoginModel();
        $user = $LoginModel->getUserInfo($openId);

        $data['session3rd'] = $session3rd;
        $data['session_key'] = $sessionKey;
        $data['uid'] = $user['id'];
        $data['login_time'] = time();

        if ($LoginModel->saveLoginSession($data)) {
            return $user;
        } else {
            return false;
        }
    }
}